package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.Admin;
import com.dropdb.demo.bean.AdminExample;
import com.dropdb.demo.bean.bo.AdminAdminListBO;
import com.dropdb.demo.bean.bo.BaseData;
import com.dropdb.demo.bean.vo.AdminData;
import com.dropdb.demo.config.SystemPermissionsConfig;
import com.dropdb.demo.mapper.AdminMapper;
import com.dropdb.demo.mapper.PermissionMapper;
import com.dropdb.demo.mapper.RoleMapper;
import com.dropdb.demo.service.AdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    AdminMapper adminMapper;
    @Autowired
    RoleMapper roleMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Resource(name = "sysPmConfig")
    SystemPermissionsConfig systemPermissionsConfig;

    @Transactional
    @Override
    public AdminData create(Admin admin) {
        Admin toDb = new Admin();
        toDb.setAvatar(admin.getAvatar());

        //未使用加盐密码哈希
        Md5Hash md5Hash = new Md5Hash(admin.getPassword(),admin.getUsername(),1);
        String pwd = md5Hash.toHex().toLowerCase();
        toDb.setPassword(pwd);
        toDb.setRoleIds(admin.getRoleIds());
        toDb.setUsername(admin.getUsername());
        toDb.setAddTime(new Date());
        toDb.setUpdateTime(toDb.getAddTime());

        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria()
                .andUsernameEqualTo(toDb.getUsername())
                .andDeletedEqualTo(false);
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        if (null != admins && !admins.isEmpty()) {
            return null;
        }

        int i = adminMapper.insertSelective(toDb);
        if (1 != i) {
            return null;
        }
        admins = adminMapper.selectByExample(adminExample);
        if (null == admins || admins.isEmpty()) {
            return null;
        }
        admin = admins.get(0);
        AdminData adminData = new AdminData(admin.getId(), admin.getAvatar(), admin.getUsername(), admin.getRoleIds());
        return adminData;
    }

    @Transactional
    @Override
    public AdminData update(Admin admin) {
        Admin toDb = new Admin();
        toDb.setAvatar(admin.getAvatar());

        //未使用加盐密码哈希
        if (null != admin.getPassword()) {
            Md5Hash md5Hash = new Md5Hash(admin.getPassword(),admin.getUsername(),1);
            String pwd = md5Hash.toHex().toLowerCase();
            toDb.setPassword(pwd);
        }
        toDb.setRoleIds(admin.getRoleIds());
        toDb.setUsername(admin.getUsername());
        toDb.setId(admin.getId());
        toDb.setUpdateTime(new Date());
        if (null != admin.getLastLoginIp()) {
            toDb.setLastLoginIp(admin.getLastLoginIp());
        }
        if (null != admin.getLastLoginTime()) {
            toDb.setLastLoginTime(admin.getLastLoginTime());
        }

        AdminExample adminExample = new AdminExample();
        adminExample.createCriteria()
                .andUsernameEqualTo(toDb.getUsername())
                .andDeletedEqualTo(false);
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        if (null != admins && !admins.isEmpty() && !admins.get(0).getId().equals(admin.getId())) {
            return null;
        }

        int i = adminMapper.updateByPrimaryKeySelective(toDb);
        if (1 != i) {
            return null;
        }

        //返回数据
        admin = adminMapper.selectByExample(adminExample).get(0);
        AdminData adminData = new AdminData(admin.getId(), admin.getAvatar(), admin.getUsername(), admin.getRoleIds());
        return adminData;
    }

    @Override
    public int delete(Admin admin) {
        if (null == admin.getId()) {
            return -1;
        }
        Admin deleted = new Admin();
        deleted.setId(admin.getId());
        deleted.setDeleted(true);
        return adminMapper.updateByPrimaryKeySelective(deleted);
    }

    @Override
    public BaseData<AdminData> list(AdminAdminListBO bo) {
        AdminExample adminExample = new AdminExample();
        AdminExample.Criteria criteria = adminExample.createCriteria();
        if (null != bo.getUsername()) {
            criteria.andUsernameLike("%" + bo.getUsername() + "%");
        }
        criteria.andDeletedEqualTo(false);
        adminExample.setOrderByClause(bo.getSort() + " " + bo.getOrder());
        PageHelper.startPage(bo.getPage(), bo.getLimit());
        List<Admin> admins = adminMapper.selectByExample(adminExample);
        PageInfo<Admin> pageInfo = new PageInfo<>(admins);
        long total = pageInfo.getTotal();

        List<AdminData> adminList = new ArrayList<>(admins.size());
        for (Admin a : admins) {
            adminList.add(new AdminData(a.getId(), a.getAvatar(), a.getUsername(), a.getRoleIds()));
        }
        return new BaseData<>(total,adminList);
    }


    /**
     * 获取登录信息
     * @param admin
     * @return
     */
    @Override
    public Map<String, Object> getLoginInfo(Admin admin) {
        HashMap<String, Object> info = new HashMap<>();
        // 获取role信息
        List<String> roles = roleMapper.selectRoleNameByRoleId(admin.getRoleIds());
        info.put("roles", roles);
        // 获取姓名
        info.put("name", admin.getUsername());
        // 图片信息
        info.put("avatar", admin.getAvatar());
        // 获取权限
        List<String> perms = permissionMapper.selectPermsNameByRoleId(admin.getRoleIds());
        if (perms.get(0).equals("*")) {
            info.put("perms", perms);
            return info;
        }
        ArrayList<String> permsApi = new ArrayList<>();
        List<SystemPermissionsConfig.ModulePermissions> permissions = systemPermissionsConfig.getSystemPermissions();
        for (SystemPermissionsConfig.ModulePermissions permission : permissions) {
            List<SystemPermissionsConfig.SubModulePermissions> subModulePermissions = permission.getChildren();
            for (SystemPermissionsConfig.SubModulePermissions subModulePermission : subModulePermissions) {
                List<SystemPermissionsConfig.LeafPermission> leafPermissionList = subModulePermission.getChildren();
                for (SystemPermissionsConfig.LeafPermission leafPermission : leafPermissionList) {
                    // 获取到具体权限
                    String id = leafPermission.getId();
                    for (String perm : perms) {
                        if (id.equals(perm)) permsApi.add(leafPermission.getApi());
                    }
                }
            }
        }
        info.put("perms", permsApi);
        return info;
    }
}
